package telebase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

public class ContactsView extends javax.swing.JFrame {

    private DB db = new DB();
    private ArrayList<ContObj> LOList = new ArrayList<ContObj>();
    private DocumentListener TextListener = new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            String filter = "";
            try {
                filter = e.getDocument().getText(0, e.getDocument().getLength());
            } catch (BadLocationException ex) {
                System.out.println(ex.toString());
            }
            RefreshList(filter);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            String filter = "";
            try {
                filter = e.getDocument().getText(0, e.getDocument().getLength());
            } catch (BadLocationException ex) {
                System.out.println(ex.toString());
            }
            RefreshList(filter);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            System.out.println("changeUpdate");
        }
    };

    public ContactsView() {
        initComponents();

        i18n();

        jTextField1.getDocument().addDocumentListener(TextListener);
        jList1.setCellRenderer(new ContactsViewListRenderer());

        WaitingWindow waw = new WaitingWindow();
        RefreshListDB();
        RefreshList("");
        waw.close();
    }

    private void i18n() {
        setTitle(i18n.get("conview_title") + " - " + Vars.getVersion());

        jButton1.setText(i18n.get("conview_close"));
        jButton2.setText(i18n.get("conview_options"));
        jButton3.setText(i18n.get("conview_edit"));
        jLabel1.setText(i18n.get("conview_search"));

        if (Vars.prop.getProperty("AccessMode").equals("Admin")) {
            jButton3.setEnabled(true);
        } else {
            jButton3.setEnabled(false);
        }

        pack();
    }

    private void RefreshListDB() {
        LOList.clear();
        ArrayList<Integer> Klist = new ArrayList<Integer>();

        ResultSet rs = db.getResultSet("select * from contacts order by contactname");
        try {
            while (rs.next()) {
                Klist.add(rs.getInt("k"));
            }
        } catch (SQLException ex) {
            System.out.println("ContactsView.RefreshList: " + ex.toString());
        }
        db.closeResultSet();

        for (Integer k : Klist) {
            LOList.add(new ContObj(k));
        }
    }

    private void RefreshList(String filter) {
        DefaultListModel lm = new DefaultListModel();
        String contname = "";
        Boolean check = false;
        filter = filter.toLowerCase();
        for (ContObj lo : LOList) {
            check = false;
            contname = lo.getName().toLowerCase();
            for (String cphone : lo.getPhones().values()) {
                cphone = cphone.toLowerCase();
                cphone = cphone.replace(" ", "");
                cphone = cphone.replace("(", "");
                cphone = cphone.replace(")", "");
                cphone = cphone.replace("-", "");
                cphone = cphone.replace("+", "");
                if (cphone.contains(filter)) {
                    check = true;
                }
            }
            if (contname.contains(filter)) {
                check = true;
            }
            if (check) {
                lm.addElement(lo);
            }
        }
        jList1.setModel(lm);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(670, 520));

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Search:");

        jButton2.setText("Options");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Edit contacts");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 585, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 646, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 373, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        OptionsDialog dlg = new OptionsDialog(null, true);
        dlg.setLocationRelativeTo(this);
        dlg.setVisible(true);
        WaitingWindow waw = new WaitingWindow();
        i18n();
        jTextField1.setText("");
        RefreshListDB();
        RefreshList("");
        waw.close();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        ContObj lo = (ContObj) jList1.getModel().getElementAt(jList1.getSelectedIndex());
        ContactsViewDetails dlg = new ContactsViewDetails(null, true, lo);
        dlg.setLocationRelativeTo(this);
        dlg.setVisible(true);
    }//GEN-LAST:event_jList1MouseClicked

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ContactsEditView dlg = new ContactsEditView(null, true);
        dlg.setLocationRelativeTo(this);
        dlg.setVisible(true);
        WaitingWindow waw = new WaitingWindow();
        jTextField1.setText("");
        RefreshListDB();
        RefreshList("");
        waw.close();
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
